package locationHelper

import (
	"awesomeTask/config"
	"awesomeTask/system/echo"
	"runtime"

	//"awesomeTask/system/echo"
	"awesomeTask/system/helper"
	"awesomeTask/system/http"
	"errors"
	"regexp"
)

/**
获取外网IP地址
*/
func GetNetworkIp() (string, error) {
	client := http.HttpClient{}
	client.SetHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36")
	res, err := client.Get("https://2023.ip138.com/")
	if err != nil {
		return "", err
	}
	re, err := regexp.Compile(`IP: (.*?)<`)
	if err != nil {
		panic(err.Error())
	}
	ipInfo := re.FindStringSubmatch(res)
	if len(ipInfo) >= 2 {
		return ipInfo[1], nil
	}
	return "", errors.New("无法获取到公网IP地址,请检查 http://pv.sohu.com/cityjson 此地址是否已经失效")
}

func GetLocationInfo() (map[string]string, error) {
	defer func() {
		if r := recover(); r != nil {
			buf := make([]byte, 1<<16)
			runtime.Stack(buf, true)
			echo.Red("获取本机的坐标地址出现异常,可视化界面可能会收到影响" + r.(error).Error() + string(buf))
		}
	}()
	ip, err := GetNetworkIp()
	if err != nil {
		return make(map[string]string), err
	}
	return GetLocationByIp(ip)
}
func GetLocationByIp(ip string) (map[string]string, error) {
	client := http.HttpClient{}
	res, err := client.
		SetGetParams("ak", config.GetConfigByKey("baiduSdkAk").(string)).
		SetGetParams("ip", ip).
		SetGetParams("coor", "bd09ll").
		Get("http://api.map.baidu.com/location/ip")
	if err != nil {
		return make(map[string]string), err
	}
	jsonRes := helper.JsonDecode(res).(map[string]interface{})["content"].(map[string]interface{})
	resMap := make(map[string]string)
	resMap["address"] = jsonRes["address"].(string)
	resMap["lng"] = jsonRes["point"].(map[string]interface{})["x"].(string)
	resMap["lat"] = jsonRes["point"].(map[string]interface{})["y"].(string)
	dir := config.GetConfigByKey("fileSystem").(string) + "/cache/"
	path := dir + "location.json"
	if helper.CheckFileIsExist(path) {
		data := helper.JsonDecode(helper.ReadFileAsString(path)).(map[string]interface{})
		data["ip"] = resMap
		helper.Mkdir(dir, 0777)
		helper.WriteFile(path, helper.JsonEncode(data), 0777)
	} else {
		data := map[string]interface{}{
			ip: resMap,
		}
		helper.Mkdir(dir, 0777)
		helper.WriteFile(path, helper.JsonEncode(data), 0777)
	}
	return resMap, err
}
